const explain = require("explain")
const uniID = require('uni-id')

module.exports = class video extends explain.service {
	async getVideosByCourseId(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		const dbCmd = db.command
		const $ = dbCmd.aggregate
		return await db.collection('videos').aggregate()
			.match({
				course_id: params.courseId,
			})
			.lookup({
				from: 'study-records',
				let: {
					id: '$_id'
				},
				pipeline: $.pipeline()
					.match(dbCmd.expr($.eq(['$video_id', '$$id'])))
					.done(),
				as: 'study_record'
			})
			.replaceRoot({
				newRoot: $.mergeObjects([{
					record: $.arrayElemAt(['$study_record', 0])
				}, '$$ROOT'])
			})
			.project({
				study_record: 0
			})
			.sort({
				order: 1
			})
			.end()
	}
}
